package my.example.samplegridview;

import java.io.File;
import java.util.Vector;

import my.example.samplegridview.modal.category;
import my.example.samplegridview.modal.product;
import my.example.samplegridview.modal.product_to_category;
import o2s.contentprovider.datacontentprovider;
import o2s.utils.imageHelper;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class syncProcess {
	public static void Sync(Context context){
		ProgressDialog progressDialog;
		progressDialog = new ProgressDialog(context);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setMessage("Loading...");
		progressDialog.setCancelable(true);
		SyncDataTask sdt = new SyncDataTask(progressDialog,context);
		sdt.execute();
	}
	
	private static class SyncDataTask extends AsyncTask<Void, Integer, Void> {

	    private final ProgressDialog progress;
	    private int progressIndex;
	    private Context context;
	    private String[] message = {"Syncing data...","Syncing product images...","Syncing category images..."};
	    private String currentStage = "";
	    private String previouStage = "";
	    private int totalPercentage = 0;
	    private static int currentPercentage = 0;
	    private Object mLock = new Object();;
		
		public SyncDataTask(ProgressDialog progress , Context context) {
	        this.progress = progress;
	        this.progressIndex = 0;
	        this.context = context;
	    }

		@Override
	    protected void onPreExecute() {
			// 1 - transferring data
			// 2 - transferring images for products
			// 3 - transferring images for categories
			progress.setMax(3);
			progress.show();
	    }
		
		@Override
	    protected void onProgressUpdate(final Integer... values) {
			
			if(currentStage.compareTo("END") == 0){
				progress.cancel();
			}
			else if(currentStage!=previouStage){
				previouStage = currentStage;
				progress.setMessage(currentStage);
				progress.setMax(totalPercentage);
				progress.setProgress(0);
			}
			else{
				progress.incrementProgressBy(SyncDataTask.currentPercentage);
			}
	    }
		
		@Override
		protected Void doInBackground(Void... arg0) {
			
			//-------Start : Clearing Database---------------
			currentStage = "Clearing Database...";
			totalPercentage = 1;
			publishProgress();
			
			DeleteDb(context);
			
			currentPercentage = 1;
			publishProgress();
			//-------End : Clearing Database---------------
			
			//-------Start : Refreshing Database---------------
			currentStage = "Refreshing Database...";
			totalPercentage = 1;
			String[] rere = {"0"};
			publishProgress();
			
			context.getContentResolver().query(product_to_category.CONTENT_URI, null, "category_id=?",rere, null);
			
			currentPercentage = 1;
			publishProgress();
			//-------End : Refreshing Database---------------
			
			//-------Start : Loading Product Images---------------
			currentStage = "Loading Product Images...";
			Vector<product> products = product.SelectProducts(context);
			totalPercentage = products.size();
			
			String image = "";
			String plainimagepath = "";
			int index = 0;
			for(int i = 0 ; i < products.size() ; i++){
				plainimagepath = products.get(i).getImage();
				if(plainimagepath.length() > 0){
					index = plainimagepath.lastIndexOf("/");
					image = plainimagepath.substring(index+1);
					
					while(!imageHelper.downloadFromUrl(adminmenu.imageUrl + plainimagepath, image, context))
					currentPercentage++;
					publishProgress();
				}
			}
			//-------End : Loading Product Images---------------
			
			//-------Start : Loading Category Images---------------
			
			currentStage = "Loading Category Images...";
			Vector<category> categories = category.SelectCategories(context);
			totalPercentage = categories.size();
			publishProgress();
			
			image = "";
			plainimagepath = "";
			index = 0;
			for(int i = 0 ; i < categories.size() ; i++){
				plainimagepath = categories.get(i).getImage();
				if(plainimagepath.length() > 0){
					index = plainimagepath.lastIndexOf("/");
					image = plainimagepath.substring(index+1);
					
					while(!imageHelper.downloadFromUrl(adminmenu.imageUrl + plainimagepath, image, context))
					currentPercentage++;
					publishProgress();
				}
			}
			
			//-------End : Loading Category Images---------------
			
			currentStage = "END";
			publishProgress();
			
			return null;
		}

		@Override
		protected void onPostExecute(Void result){
			progress.cancel();
		}
	}
	
	public static void DeleteDb(Context context){
		Log.d("o2s", "Start deleting Db");
		if(datacontentprovider.dbHelper != null){
			datacontentprovider.dbHelper.getWritableDatabase().close();
			datacontentprovider.dbHelper.close();
		}
		
		String dbPath = context.getApplicationInfo().dataDir + "/databases/O2S.db";
		File f = new File(dbPath);
		if(f.exists()){
			if(!context.deleteDatabase("O2S.db"))
				Log.d("f","f");
			else{
				//datacontentprovider.dbHelper.onCreate(context.openOrCreateDatabase("O2S.db", Context.MODE_PRIVATE, null));
			}
		}
	}
}
